<!-- src/views/dept/DeptList.vue -->
<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useDeptStore } from '@/stores/deptStore.js';
import DeptEdit from '@/views/system/DeptEdit.vue';

const deptStore = useDeptStore();
const tableData = ref([]);
const deptEditRef = ref(null);
const router = useRouter();

// 添加创建部门表单的引用
const createDeptFormRef = ref(null);
// 添加创建部门对话框可见性状态
const createDialogVisible = ref(false);

// 创建部门表单数据
const createDeptForm = ref({
  name: '',
  parentId: '',
  sort: '',
  description: ''
});

// 创建部门表单验证规则
const createDeptRules = ref({
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择父部门', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
});

// 部门树数据
const deptTreeOptions = ref([]);

onMounted(() => {
  deptStore.getDeptList();
  tableData.value = deptStore.deptList;
});

const handleCurrentChange = (val) => {
  deptStore.pageInfo.pageNum = val;
  deptStore.getDeptList();
};

const handleEdit = (deptInfo) => {
  deptEditRef.value.show(deptInfo);
};

const handleViewDetail = (deptInfo) => {
  deptStore.deptDetail = deptInfo;
  router.push(`/dept/deptDetail`);
};

const handleDelete = async (deptInfo) => {
  try {
    await deptStore.deleteDept(deptInfo.id);
  } catch (error) {
    console.error('删除部门失败', error);
  }
};

// 修改函数以正确处理 isDelete 字段
const getRowClass = ({ row }) => {
  // 检查 row 对象中是否有 isDelete 字段，并且其值为 1
  return row.isDelete === 1 ? 'deleted-row' : '';
};

// 显示创建部门对话框
const showCreateDialog = async () => {
  // 重置表单
  Object.assign(createDeptForm.value, {
    name: '',
    parentId: '',
    sort: '',
    description: ''
  });

  createDialogVisible.value = true;
  // 加载部门树数据
  await loadDeptTree();
};

// 获取部门树数据并转换为下拉选项
const loadDeptTree = async () => {
  try {
    await deptStore.getDeptTree();

    // 转换树形结构为扁平化选项列表
    const flattenTree = (nodes, level = 0) => {
      const result = [];
      nodes.forEach(node => {
        // 添加当前节点
        result.push({
          value: node.id,
          label: '　'.repeat(level) + node.name, // 添加缩进显示层级关系
          disabled: false // 创建时不需要禁用任何选项
        });

        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          result.push(...flattenTree(node.children, level + 1));
        }
      });
      return result;
    };

    // 转换数据格式以适配 el-select
    deptTreeOptions.value = flattenTree(deptStore.deptTree);
  } catch (error) {
    console.error('获取部门树失败:', error);
  }
};

// 提交创建部门表单
const submitCreateForm = () => {
  createDeptFormRef.value?.validate().then(async () => {
    try {
      const formData = {
        name: createDeptForm.value.name,
        parentId: parseInt(createDeptForm.value.parentId),
        sort: parseInt(createDeptForm.value.sort),
        description: createDeptForm.value.description || ''
      };

      await deptStore.createDept(formData);
      createDialogVisible.value = false;
      // 重置表单
      createDeptFormRef.value?.resetFields();
    } catch (error) {
      console.error('创建部门失败', error);
    }
  }).catch(() => {
    console.log('表单校验失败');
  });
};

// 关闭创建部门对话框
const closeCreateDialog = () => {
  createDialogVisible.value = false;
  createDeptFormRef.value?.resetFields();
};
</script>

<template>
  <div class="dept-container">
    <!-- 添加创建部门按钮 -->
    <div class="toolbar">
      <el-button type="primary" @click="showCreateDialog">创建部门</el-button>
    </div>

    <el-table :data="tableData" class="dept-table" :row-class-name="getRowClass">
      <el-table-column label="部门编号" prop="id" width="150"></el-table-column>
      <el-table-column label="部门名称" prop="name"></el-table-column>
      <el-table-column label="父部门编号" prop="parentId" width="120"></el-table-column>
      <el-table-column label="创建时间" prop="createdTime" ></el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isDelete === 1 ? 'danger' : 'success'">
            {{ scope.row.isDelete === 1 ? '已删除' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :total="deptStore.pageInfo.total"
      :page-size="deptStore.pageInfo.pageSize"
      :current-page="deptStore.pageInfo.pageNum"
      @current-change="handleCurrentChange"
      layout="prev, pager, next, jumper, ->, total"
      background
      class="pagination"
    />

    <DeptEdit ref="deptEditRef" />

    <!-- 创建部门对话框 -->
    <el-dialog
      title="创建部门"
      v-model="createDialogVisible"
      width="50%"
      @close="closeCreateDialog"
    >
      <el-form
        :model="createDeptForm"
        :rules="createDeptRules"
        ref="createDeptFormRef"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="createDeptForm.name" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="父部门" prop="parentId">
          <el-select
            v-model="createDeptForm.parentId"
            placeholder="请选择父部门"
            style="width: 100%"
            clearable
            filterable
          >
            <el-option
              v-for="item in deptTreeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="createDeptForm.sort" placeholder="请输入排序值"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="createDeptForm.description" placeholder="请输入描述" type="textarea"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitCreateForm">确定</el-button>
          <el-button @click="closeCreateDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped>
.dept-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}

.dept-table {
  margin-bottom: 20px;
}

.dept-table :deep(.el-table__header th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

.pagination {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button--primary) {
  --el-button-bg-color: #1a56db;
  --el-button-border-color: #1a56db;
}

:deep(.el-button--danger) {
  --el-button-bg-color: #e11d48;
  --el-button-border-color: #e11d48;
}

/* 添加已删除行的样式 */
:deep(.deleted-row) {
  background-color: #fef0f0 !important;
  color: #f56c6c;
}

:deep(.deleted-row .cell) {
  text-decoration: line-through;
}
</style>
